<template>
  <div class="wrapper">
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/welcome' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card>
      <el-button
        type="primary"
        @click="onRoleOption('add')"
      >添加角色</el-button>
      <el-table
        :data="rolesList"
        style="width: 100%"
        border
        stripe
      >
        <el-table-column
          label="more"
          width="100"
          type="expand"
        >
          <template slot-scope="scope">
            <el-row
              v-for="(data1,index1) in scope.row.children"
              :key="data1.id"
              :class="[index1===0?'':'boder-top','vcenter']"
            >
              <!-- :class="{'boder-top':index===0}" -->
              <!-- :class="[index===0?'':'boder-top','vcenter']" -->

              <el-col :span="4">
                <el-tag
                  closable
                  @close="removeRight(scope.row,data1)"
                > {{data1.authName}}</el-tag>
                <i class="el-icon-caret-right"></i>
              </el-col>
              <el-col :span="20">

                <el-row
                  :gutter="20"
                  v-for="(data2,index2) in data1.children"
                  :key="data2.id"
                  :span="4"
                  :class="[index2===0?'':'boder-top','vcenter','mHeight']"
                >
                  <el-col :span="4">
                    <el-tag
                      type="success"
                      closable
                      @close="removeRight(scope.row,data2)"
                    > {{data2.authName}}</el-tag>
                    <i class="el-icon-caret-right"></i>
                  </el-col>
                  <el-col :span="20">
                    <el-tag
                      type="warning"
                      closable
                      v-for="data3 in data2.children"
                      :key="data3.id"
                      class="mMargin"
                      :gutter="20"
                      @close="removeRight(scope.row,data3)"
                    > {{data3.authName}}</el-tag>
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
            <!-- pre可以格式化json数据 -->
            <!-- <pre> {{scope.row}}</pre> -->
          </template>
        </el-table-column>
        <el-table-column
          label="#"
          width="100"
          type="index"
        >
        </el-table-column>
        <el-table-column
          prop="roleName"
          label="角色名称"
        >
        </el-table-column>
        <el-table-column
          prop="roleDesc"
          label="角色描述"
        >
        </el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-button
              type="primary"
              icon="el-icon-edit"
              size="mini"
              @click="onRoleOption(scope.row)"
            >编辑</el-button>
            <el-button
              type="danger"
              icon="el-icon-delete"
              size="mini"
              @click="onDelete(scope.row)"
            >删除</el-button>
            <el-tooltip
              class="item"
              effect="dark"
              content="分配权限"
              placement="right"
              :enterable="false"
            >

              <el-button
                type="warning"
                icon="el-icon-setting"
                @click="allotRoleClick(scope.row)"
                size="mini"
              >分配权限</el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    <!-- 添加角色和修改角色 -->
    <el-dialog
      :title="dialogTitle"
      :visible.sync="dialogRole"
      width="50%"
      :close-on-click-modal="false"
      @close="onCancle('add')"
    >
      <el-form
        :model="roleParams"
        :rules="rules"
        label-width="100px"
        ref="roleForm"
      >
        <el-form-item
          label="角色名称"
          prop="roleName"
        >
          <el-input
            v-model="roleParams.roleName"
            autocomplete="off"
          ></el-input>
        </el-form-item>
        <el-form-item
          label="角色描述"
          prop="roleDesc"
        >
          <el-input v-model="roleParams.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <span
        slot="footer"
        class="dialog-footer"
      >
        <el-button @click="dialogRole = false">取 消</el-button>
        <el-button
          type="primary"
          @click="onCommit"
        >确 定</el-button>
      </span>
    </el-dialog>

    <!-- 分配权限 -->
    <el-dialog
      title="分配权限"
      :visible.sync="dialogAllotRole"
      width="50%"
      :close-on-click-modal="false"
      @close="dialogAllotRole=false"
    >
      <el-tree
        :data="rightsList"
        show-checkbox
        node-key="id"
        ref="roleTree"
        :default-expand-all="true"
        :props="defaultTree"
        :default-checked-keys="treeCheckDataId"
      >
      </el-tree>
      <span
        slot="footer"
        class="dialog-footer"
      >
        <el-button @click="dialogAllotRole = false">取 消</el-button>
        <el-button
          type="primary"
          @click="onRoleCommit"
        >确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
export default {
  data () {
    const validatePass = (rule, value, callback) => {
      //自定义验签规则，这里可以写正则
      if (value === '') {
        callback(new Error('角色描述不能为空'))
      } else {
        callback()
      }
    }
    return {
      rolesList: [],
      rightsList: [],
      dialogRole: false,
      dialogTitle: '添加角色',
      roleParams: {
        roleName: '',
        roleDesc: ''
      },
      defaultTree: {
        children: 'children',
        label: 'authName'
      },
      dialogAllotRole: false,
      roleEditId: '',
      treeRoleId: '',
      treeCheckDataId: [],
      rules: {
        roleName: [
          { required: true, message: '请输入角色名称', trigger: 'blur' },
          { min: 3, max: 10, message: '角色名称在 3 到 10 个字符', trigger: 'blur' }
        ],
        roleDesc: [
          { required: true, validator: validatePass, trigger: 'blur' }
        ]
      }
    }
  },
  created () {
    this.getRolesList()
  },
  methods: {
    async getRolesList () {
      const { data: res } = await this.$http.get('roles');
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg);
      this.rolesList = res.data;
    },
    async getRightsList () {
      const { data: res } = await this.$http.get('rights/tree');
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg);
      this.rightsList = res.data;
    },
    async setRoleData () {
      const { data: res } = await this.$http.post('roles', this.roleParams);
      if (res.meta.status !== 201) return this.$message.error(res.meta.msg);
      this.$message.success(res.meta.msg);
      this.getRolesList();
    },
    async deleteRole (id) {
      const { data: res } = await this.$http.delete(`roles/${id}`);
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg);
      this.$message.success(res.meta.msg);
      this.getRolesList();
    },
    async editRole () {
      const { data: res } = await this.$http.put(`roles/${this.roleEditId}`, this.roleParams);
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg);
      this.$message.success(res.meta.msg);
      this.getRolesList();
    },
    async setRoleTree (idStr) {
      const { data: res } = await this.$http.post(`roles/${this.treeRoleId}/rights`, { rids: idStr });
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg);
      this.$message.success(res.meta.msg);
      this.getRolesList();
    },
    async removeRole (bigData, smallData) {
      const { data: res } = await this.$http.delete(`roles/${bigData.id}/rights/${smallData.id}`);
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg);
      this.$message.success(res.meta.msg);
      //可以改变插槽内的数据
      bigData.children = res.data;
    },
    onCancle (str) {
      this.$refs.roleForm.clearValidate()
    },
    onCommit (str) {
      this.$refs.roleForm.validate(async (result) => {
        if (!result) return;
        this.dialogRole = false;
        if (this.dialogTitle === '添加角色') {
          this.setRoleData();
        } else {
          this.editRole();
        }
      });
    },
    onDelete (data) {
      this.$confirm('此操作将永久删除该用户, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.deleteRole(data.id)
      }).catch(() => {
      });
    },
    onRoleOption (data) {
      this.dialogRole = true;
      if (data === 'add') {
        this.dialogTitle = '添加角色';
        this.roleParams.roleName = '';
        this.roleParams.roleDesc = '';
      } else {
        this.dialogTitle = '修改角色';
        this.roleParams.roleName = data.roleName;
        this.roleParams.roleDesc = data.roleDesc;
        this.roleEditId = data.id;
      }
    },
    removeRight (bigData, smallData) {
      this.$confirm('确认取消该权限, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.removeRole(bigData, smallData);
      }).catch(() => {
      });
    },
    onRoleCommit () {
      const nodes = this.$refs.roleTree.getCheckedNodes(false, true);
      const arr = nodes.map((item) => {
        return item.id;
      });
      this.setRoleTree(arr.join(','))
      this.dialogAllotRole = false;
    },
    allotRoleClick (data) {
      this.treeRoleId = data.id;
      this.dialogAllotRole = true;
      this.getRightsList();
      this.treeCheckDataId = [];
      data.children.forEach(element => {
        element.children.forEach(element2 => {
          element2.children.forEach(element3 => {
            this.treeCheckDataId.push(element3.id)
          });
        });
      });
    }
  }
}
</script>
<style lang="scss" scoped>
.mMargin {
  margin-left: 10px;
}
.mHeight {
  height: 50px;
}
</style>
